#!/bin/sh
# This file is heavily based on code from https://github.com/Xentrk/netflix-vpn-bypass/blob/master/IPSET_Netflix.sh
# Credits to https://forum.openwrt.org/u/dscpl for api.hackertarget.com code.
# Credits to https://github.com/kkeker and https://github.com/tophirsch for api.bgpview.io code.

TARGET_IPSET='wan'
TARGET_ASN='2906'
TARGET_FNAME="/var/vpn-policy-routing_tmp_AS${TARGET_ASN}"
#DB_SOURCE='ipinfo.io'
#DB_SOURCE='api.hackertarget.com'
DB_SOURCE='api.bgpview.io'

_ret=1

if [ ! -s "$TARGET_FNAME" ]; then
	if [ "$DB_SOURCE" = "ipinfo.io" ]; then
		TARGET_URL="https://ipinfo.io/AS${TARGET_ASN}"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | grep -E "a href.*${TARGET_ASN}\/" | grep -v ":" | sed "s/^.*<a href=\"\/AS${TARGET_ASN}\///; s/\" >//" > "$TARGET_FNAME"
	fi

	if [ "$DB_SOURCE" = "api.hackertarget.com" ]; then
		TARGET_URL="https://api.hackertarget.com/aslookup/?q=AS${TARGET_ASN}"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | sed '1d' > "$TARGET_FNAME"
	fi

	if [ "$DB_SOURCE" = "api.bgpview.io" ]; then
		TARGET_URL="https://api.bgpview.io/asn/${TARGET_ASN}/prefixes"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | jsonfilter -e '@.data.ipv4_prefixes[*].prefix' > "$TARGET_FNAME"
	fi
fi

if [ -s "$TARGET_FNAME" ]; then
	awk -v ipset="$TARGET_IPSET" '{print "add " ipset " " $1}' "$TARGET_FNAME" | ipset restore -! && _ret=0
fi
rm -f "$TARGET_FNAME"

return $_ret
